package http

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// RequestApi api请求方法
type RequestApi interface {
	Get(url string) (*http.Response, error)
	Post(url string, data interface{}) (*http.Response, error)
}

type Request struct {
}

func (r Request) Get(url string) (*http.Response, error) {
	resp, err := http.Get(url)
	if err != nil {
		fmt.Printf("request failed, err:%v\n", err)
		return nil, err
	}
	defer func() {
		err = resp.Body.Close()
		if err != nil {
			fmt.Printf("资源关闭失败, err:%v\n", err)
		}
	}()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("request failed, body:%v\n", err)
		return nil, err
	}
	fmt.Printf("Response body: %v \n", string(body))
	return resp, nil
}

func (r Request) Post(url string, data interface{}) (*http.Response, error) {
	// 将传过来参数进行json序列化
	jsonData, err := json.Marshal(data)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}
	// 设置请求头
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	// 关闭请求
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			fmt.Printf("Response body: %v \n", err)
		}
	}(resp.Body)
	// 读取请求体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	fmt.Printf("Response body: %v \n", string(body))
	return resp, nil
}

type Response struct {
	Request RequestApi
}

func (r *Response) SetRequestStrategy(request RequestApi) {
	r.Request = request
}

// GetRequestStrategy get方法策略
func (r *Response) GetRequestStrategy(url string) (*http.Response, error) {
	return r.Request.Get(url)
}

// PostRequestStrategy post方法策略
func (r *Response) PostRequestStrategy(url string, data interface{}) (*http.Response, error) {
	return r.Request.Post(url, data)
}
